<template>
  <div id="chat-container">
    <div class="header">
      <el-button
        icon="el-icon-arrow-left"
        class="left-button"
        @click="goBack"
        plain
        style="
          padding: 0;
          background-color: transparent;
          border: 0;
          font-size: 28px;
        "
      ></el-button>
      <span class="title"
        >{{ headerText
        }}<i
          class="el-icon-question"
          style="width: 24px; height: 24px"
          @click="userTip"
        ></i
      ></span>
      <el-button
        icon="el-icon-refresh"
        @click.stop="refreshPage"
        :disabled="refreshDisable"
        class="right-button"
        @click="refreshPage"
        plain
        style="
          padding: 0;
          background-color: transparent;
          border: 0;
          font-size: 28px;
        "
      ></el-button>
    </div>
    <div class="chat-messages" ref="ChatMessage">
      <el-scrollbar wrap-class="message-list">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-wrapper"
        >
          <div
            :class="{
              'client-message': message.sender === 'client',
              'merchant-message': message.sender === 'merchant',
            }"
          >
            <!--      头像判断      -->
            <div class="user-avatar" v-if="message.sender === 'merchant'">
              <svg
                t="1702006258443"
                class="icon"
                viewBox="0 0 1024 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="898"
                width="26"
                height="26"
              >
                <path
                  d="M222.9248 222.208h574.464c24.1664 0 43.7248-19.5584 43.7248-43.7248 0-24.1664-19.5584-43.7248-43.7248-43.7248H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248-0.0512 24.1664 19.5584 43.7248 43.7248 43.7248z"
                  fill="#757BF2"
                  p-id="899"
                ></path>
                <path
                  d="M918.784 421.12l-70.2976-153.5488a2.1504 2.1504 0 0 0-1.8944-1.2288H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.2448 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048 35.6864 0 67.3792-17.1008 87.296-43.5712 20.1728-26.8288 23.1424-62.976 9.1648-93.5424zM720.128 575.9488c-28.3648 22.8864-64.1536 36.0448-102.144 36.0448s-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-37.9904 0-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v222.3104c0 31.8976 25.856 57.7536 57.7536 57.7536H786.944c31.8976 0 57.7536-25.856 57.7536-57.7536v-221.184c-7.424 1.024-14.8992 1.6384-22.4256 1.6384-37.9904 0.0512-73.7792-13.1584-102.144-35.9936z"
                  fill="#6C6CEA"
                  p-id="900"
                ></path>
                <path
                  d="M846.592 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.2448 66.048 100.2496 66.048 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c14.8992 34.5088 46.9504 59.8016 85.4528 65.024 36.0448-76.544 56.2688-161.9968 56.2688-252.2112 0-1.3824-0.0512-2.816-0.0512-4.1984l-15.2064-33.1776a2.24768 2.24768 0 0 0-1.9456-1.28zM720.128 575.9488c-28.3648 22.8864-64.1536 36.0448-102.144 36.0448s-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-37.9904 0-73.7792-13.1584-102.144-36.0448a162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v222.3104c0 31.8976 25.856 57.7536 57.7536 57.7536h133.0176c175.0528-29.3888 324.0448-135.4752 411.2384-282.5216-22.3744-5.888-43.1616-16.384-61.0304-30.7712z"
                  fill="#757BF2"
                  p-id="901"
                ></path>
                <path
                  d="M700.2624 134.7584H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248 0 24.1664 19.5584 43.7248 43.7248 43.7248h464.896a592.5888 592.5888 0 0 0 12.4416-87.4496zM676.3008 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-12.2368 28.2624-10.3424 61.1328 6.656 86.784 19.5584 29.4912 53.0944 48.9472 91.136 48.9472 44.9536 0 83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c16.7424 38.8096 55.296 66.048 100.2496 66.048s83.5072-27.2384 100.2496-66.048a2.048 2.048 0 0 1 3.7888 0c3.072 7.168 6.9632 13.9264 11.4176 20.224 67.4816-67.8912 118.6304-152.0128 147.0976-246.0672zM399.1552 611.2768a162.48832 162.48832 0 0 1-87.552-35.3792 162.42176 162.42176 0 0 1-102.144 36.0448c-10.24 0-20.3776-0.9728-30.2592-2.816v73.7792c79.104-9.3184 153.4976-34.2528 219.9552-71.6288z"
                  fill="#8486F8"
                  p-id="902"
                ></path>
                <path
                  d="M497.408 134.7584H222.9248c-24.1664 0-43.7248 19.5584-43.7248 43.7248 0 24.1664 19.5584 43.7248 43.7248 43.7248h224.3072c19.0976-27.5456 35.8912-56.7808 50.176-87.4496zM413.3888 266.3424H180.5312c-0.8192 0-1.5872 0.512-1.8944 1.2288L111.6672 422.5024c-5.1712 11.8784-7.6288 24.6272-7.68 37.2736 122.7264-30.6688 230.3488-99.584 309.4016-193.4336z"
                  fill="#8D92F8"
                  p-id="903"
                ></path>
              </svg>
            </div>
            <template v-if="message.sender === 'client'">
              <img
                src="@/assets/images/avatar.jpg"
                alt="Avatar"
                class="user-avatar"
              />
            </template>
            <div class="message-content">
              <div class="message-timestamp">{{ message.createTime }}</div>
              {{ message.content }}
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        placeholder="输入消息"
        class="input-message"
      ></el-input>
      <el-button @click="sendMessage" type="primary" :disabled="sendBtnDisable"
        >发送</el-button
      >
    </div>
  </div>
</template>

<script>
import service from "@/api/client/index.js";
import axios from "axios";
export default {
  props: {
    // 当前用户角色
    userRole: {
      type: String,
      default: "client",
    },
  },
  data() {
    return {
      //标题
      headerText: "车辆ID",
      //消息
      messages: [],
      // 过滤后的文本内容
      filteredContent: "",
      // 发送消息
      inputMessage: "",
      //敏感词库
      sensitiveWords: [],
      //车辆ID
      carId: "",
      // 当前页面请求响应的消息个数是否有100
      msgHas100: false,
      //分页位置
      pageNumber: -1,
      //按钮禁用状态
      sendBtnDisable: false,
      refreshDisable: false,
    };
  },
  async created() {
    this.carId = this.$route.query && this.$route.query.carId;
    if (this.carId) {
      this.sensitiveWords = this.$store.getters.sensitiveWords || [];
      if (this.sensitiveWords) {
        // 加载敏感词
        await this.loadSensitiveWords();
      }
      this.headerText += ":" + this.carId;
      //加载页面数据
      await this.init();
      document.addEventListener(
        "visibilitychange",
        this.handleVisibilityChange
      );
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.ChatMessage;
        console.log(scrollElem.scrollHeight);
        scrollElem.scrollTop = scrollElem.scrollHeight;
      });
      this.userTip();
    } else {
      //非法访问，重新路由到home页面
      this.$router.push("/client/home");
    }
  },
  mounted() {
    document
      .querySelector(".chat-messages")
      .addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    document
      .querySelector(".chat-messages")
      .removeEventListener("scroll", this.handleScroll, false);
    document.removeEventListener(
      "visibilitychange",
      this.handleVisibilityChange
    );
  },
  methods: {
    //刷新当前页面
    refreshPage() {
      this.refreshDisable = true;
      this.$router.go(0);
    },
    // 用户提示
    userTip() {
      const h = this.$createElement;
      let msg = [];
      msg.push(
        h(
          "p",
          { style: "color: rgb(7 67 238 / 49%);" },
          `商家未回复之前, 只能发送三条信息`
        )
      );
      msg.push(h("p", { style: "color: #DB09097C" }, `右上角🔄更新消息状态`));
      this.$alert(h("p", null, msg), "提示", {
        confirmButtonText: "确定",
        callback: (action) => {},
      });
    },
    goBack() {
      // 返回首页的操作，可以使用路由实现
      this.$router.push("/client/home");
    },
    //加载聊天信息
    async init() {
      await service
        .getEvaluationData(this.carId, this.pageNumber)
        .then((resp) => {
          if (this.pageNumber === -1) {
            this.messages = resp.data || [];
          } else {
            this.messages = (resp.data || []).concat(this.messages);
          }
          this.msgHas100 = 100 === (resp.data || []).length;
          this.loading = false;
        });
    },
    //移动到页面底部
    scrollToBottom() {
      // this.$nextTick 将回调延迟到下次DOM更新循环之后执行。在修改数据之后立即使用它，然后等待DOM更新
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.ChatMessage;
        console.log("scrollHeight: ", scrollElem.scrollHeight);
        // scrollElem.scrollTop = scrollElem.scrollHeight
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: "smooth",
        });
      });
    },
    /**
     * 发送消息
     * @returns {Promise<void>}
     */
    async sendMessage() {
      this.sendBtnDisable = true;
      //判断倒数第三条是否存在商家的回复信息
      let count = 0;
      for (let i = this.messages.length - 1; ; i--) {
        if (i < 0) {
          break;
        }
        if (this.messages[i].sender === "merchant") {
          //三条消息内，有商家回复跳出循环
          break;
        }
        count++;
        if (this.messages[i].sender !== "merchant" && count === 3) {
          this.$modal.msgWarning("商家未回复之前, 您只可发送三条信息");
          this.sendBtnDisable = false;
          return;
        }
        if (count === 3) break;
      }
      if (!this.inputMessage || this.inputMessage.trim().length === 0) {
        this.$modal.msgWarning("不能发送空文本");
        this.sendBtnDisable = false;
        return;
      }
      // 处理发送消息的逻辑，可以将新消息添加到messages数组中
      await this.filterContent();
      const newMessage = {
        sender: "client", // 或 'merchant'
        content: this.filteredContent,
      };
      //将消息发送给后台存储
      await service.feedBack(this.carId, newMessage);

      if (this.messages.length > 100) {
        //pageNum置为-1
        this.pageNumber = -1;
        this.messages = [];
      }
      //重新获取页面数据
      await this.init();
      //滚动到底部
      this.scrollToBottom();
      this.inputMessage = ""; // 清空输入框
      this.sendBtnDisable = false;
    },
    //加載敏感詞
    async loadSensitiveWords() {
      try {
        const files = [
          "广告.txt",
          "色情类.txt",
          "涉枪涉爆违法信息关键词.txt",
          "网址.txt",
          "政治类.txt",
        ];
        const sensitiveWords = [];
        // 遍历读取每个敏感词文件
        for (const file of files) {
          const response = await axios.get(`/sensitive_words/${file}`);
          const words = response.data
            .split("\n")
            .map((word) => word.trim())
            .filter((word) => word !== "");
          sensitiveWords.push(...words);
        }
        //将敏感词存储到vuex中
        await this.$store.commit("sensitiveWords/LOAD_DATA", sensitiveWords);
        this.sensitiveWords = sensitiveWords;
      } catch (error) {
        console.error("Failed to load sensitive words", error);
      }
    },
    /**
     * 过滤文本内容
     */
    filterContent() {
      // 过滤敏感词
      let filteredContent = this.inputMessage;
      this.sensitiveWords.forEach((word) => {
        const regExp = new RegExp(word, "gi");
        filteredContent = filteredContent.replace(
          regExp,
          "*".repeat(word.length)
        );
      });
      // 更新过滤后的文本内容
      this.filteredContent = filteredContent;
    },
    // 鼠标滚动事件
    handleScroll() {
      // 变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = document.querySelector(".chat-messages").scrollTop;
      // 滚动条到顶部的条件
      // loading防止事件重复触发
      if (!this.loading && scrollTop < 50) {
        this.loading = true;
        if (this.loading) {
          if (this.msgHas100) {
            this.pageNumber -= 100; // 页数+1
            // 重新加载数剧
            this.init();
          }
        }
      }
    },
    /**
     * 判断用户视角是否已离开当前页面
     */
    async handleVisibilityChange() {
      if (document.visibilityState === "hidden") {
        // 用户离开当前页面的逻辑
        console.log("User switched to another tab or minimized the window.");
      } else {
        // 用户返回当前页面的逻辑
        console.log("User returned to the page.");
        await this.init();
      }
      this.$nextTick(() => {
        // dom 元素更新后执行滚动条到底部 否则不生效
        let scrollElem = this.$refs.ChatMessage;
        console.log(scrollElem.scrollHeight);
        scrollElem.scrollTop = scrollElem.scrollHeight;
      });
    },
  },
};
</script>

<style scoped lang="scss">
#chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #409eff;
  color: #fff;
  padding: 10px;
  display: flex;
  align-items: center;
  .left-button {
    position: absolute;
  }
  .right-button {
    position: absolute;
    right: 10px;
  }
  .title {
    display: block;
    text-align: center;
    margin: 0 auto;
    height: 55px;
    line-height: 55px;
  }
}

.chat-messages {
  margin-top: 5px;
  flex: 1;
  overflow-y: auto;
}

.message-list {
  padding: 10px;
}

.message-wrapper {
  margin-bottom: 10px;
}
.user-avatar {
  max-width: 40px; /* 设置最大宽度 */
  max-height: 40px; /* 设置最大高度 */
  border-radius: 50%; /* 使头像呈现圆形，根据需要调整 */
}

.client-message {
  display: flex;
  flex-direction: row-reverse; /* 将消息和头像的顺序反转，消息在右侧，头像在左侧 */
  align-items: center;
}

.merchant-message {
  display: flex;
  flex-direction: row; /* 消息在左侧，头像在右侧 */
  align-items: center;
}

.message-content {
  background-color: #e6f7ff; /* client消息背景色 */
  border-radius: 8px;
  padding: 8px;
  max-width: 70%;
}

.message-timestamp {
  color: #999;
  font-size: 12px;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 10px;
}

.input-message {
  flex: 1;
  margin-right: 10px;
}
</style>
